import React from 'react';
import {
	Button,
	Group,
	TextareaField,
	Toast,
	SelectField,
	SwitchField 
} from 'saltui';
const {
	Count
} = TextareaField;
import PageController from 'pages/home';
import {
	urlPrefix,
	URLS,
	nodataIcon,
	dictMap
} from '../../../app/variables';
import DB from '../../../app/db';

import Util from 'components/common/util';
import Upload from 'components/upload';

export default class PageHome extends React.Component {

	constructor(props) {
		super(props);
		let _id = props.params.id;
		if(_id == 'undefined'){
			_id = null;
		}
		let receiverId = props.params.receiverId;
		let postLevel = props.params.postLevel;
		let floorNum = props.params.comments;
		let type = "";
		if(typeof(floorNum) == "undefined" || floorNum == "undefined"){
			floorNum = '0';
			type = '2';
			postLevel = '2';
			receiverId = "";
		}else{
			type = '3';
			if(postLevel == '3'){
				floorNum = "1-200个字符";
				receiverId = "";
			}else{
				receiverId = receiverId;
			}
		}
		this.state = {
			isShowAnonymity:props.params.isShowAnonymity,
			isShowPetname:props.params.isShowPetname,
			floorNum:floorNum,
			postLevel:postLevel,
			receiverId:receiverId,
			isAnonymity:0,
			isPetname:0,
			form: {
				id: _id,
				title: '',
				content: '',
				attId: '',
				attIdJson:[],
				postId: props.params.postId,
				boardId: props.params.boardId,
				type:type
			},
			attInfo: [],
		}

		if(_id && _id != "undefined"){
			dd.biz.navigation.setTitle({
	      		title: '编辑',
			    onSuccess: function (result) {
			    },
	     		 onFail: function () {
	      		}
	    	});
		}else{
			if(floorNum == '0'){
				dd.biz.navigation.setTitle({
		      		title: '评论',
				    onSuccess: function (result) {
				    },
		     		 onFail: function () {
		      		}
		    	});
			}else{
				dd.biz.navigation.setTitle({
		      		title: '回复',
				    onSuccess: function (result) {
				    },
		     		 onFail: function () {
		      		}
		    	});
			}
			
		}
		
	}

	componentWillMount() {
		let id = this.props.params.id;
		if (id && id != "undefined") {
			this.viewPost(id);
		} else {
			this.getReplyOtherReplyInfo();
		}
	}

	componentDidMount() {

	}

	viewPost(param) {
		let t = this;
		DB.ForumModuleAPI.infoPost({
			id: param,
			checkStatus: this.props.params.checkStatus
		}).then((content) => {
			this.setState({
				isAnonymity:content.isAnonymity,
				isPetname:content.isPetname,
				form: content
			},function(){
				t.refs.upload.initData();
			});
		}).catch((error) => {

		});
	}

	getReplyOtherReplyInfo() {
		// let sourceReplyContent = salt.router.getMessage('sourceReplyContent');
		let otherId = this.props.params.otherId;
		// alert(otherId);
		if (otherId) {
			DB.ForumModuleAPI.infoPost({
				id: otherId,
				checkStatus: this.props.params.checkStatus
			}).then((content) => {
				let newContent = content.content + '\n----------------------\n';
				let form = this.state.form;
				form.content = newContent;
				this.setState({
					form
				});
			}).catch((error) => {

			});

		}
	}

	/**
	 * 表单值修改公共方法
	 * @param  {[type]}
	 * @param  {[type]}
	 * @return {[type]}
	 */
	handleChange(field, value) {
		let form = this.state.form;
		form[field] = value
		this.setState({
			form
		});
	}

	handleChangePic(field,img){
   	 var id = "";
   	 var attId="attId";
    let form = this.state.form;
    //回显
    form[field]  = img;
    //取出图片ID赋值
	    if( img.length>0){
		    for(var i=0; i<img.length;i++){
		       id = id+img[i].id+'|';
	    }      
          id=id.substring(0,id.length-1);
         }
    form[attId]  = id;
   this.setState({
			form
		});
  }

	/**
	 * 多行文件值改变事件， 支持字符长度判断
	 * @param  {[type]} field    [description]
	 * @param  {[type]} size     [description]
	 * @param  {[type]} newValue [description]
	 * @return {[type]}          [description]
	 */
	handleTextAreaChange(field, size,type, newValue) {
		// debugger;
			if(type == '0'){
				let form = this.state.form;
				form[field] = newValue
				this.setState({
					form
				});
			}else{
				if (newValue.length <= size) {
					let form = this.state.form;
					form[field] = newValue
					this.setState({
						form
					});
				}
			}
			
			
	}

	/**
	 * 表单提交
	 * @return {[type]}
	 */
	handleSubmit() {
		let showMessage;
		let showMessage1;
		if(this.state.floorNum == "0"){
			showMessage = '评论内容不能为空',
			showMessage1 = '评论内容不能输入表情'
		}else{
			showMessage = '回复内容不能为空',
			showMessage1 = '回复内容不能输入表情'
		}
		if(this.state.form.content==undefined || this.state.form.content.replace(/\s+/g,"")==""){
        Toast.show({
          type: 'error',
          content: showMessage,
          onHide: function () {}
        });
        return false;
      }

		if(this.state.form.content!=undefined || this.state.form.content!=""){
      if(isEmojiCharacter(this.state.form.content)){
        Toast.show({
        type: 'error',
        content: showMessage1,
        onHide: function () {}
     });
      return;
      }
	}
		var entity = {
			id:this.state.form.id,
			postId: this.state.form.postId,
			author: this.props.params.author,
			boardId: this.state.form.boardId,
			attId: this.state.form.attId,
			content: this.state.form.content,
			isAnonymity:this.state.isAnonymity,
			isPetname:this.state.isPetname,
			type: this.state.form.type
		};
		DB.ForumModuleAPI.replyPost({
			entity: JSON.stringify(entity),
			attInfo: JSON.stringify(this.state.attInfo),
			level:this.state.postLevel,
			receiverId:this.state.receiverId
		}).then((data) => {
			// if(this.state.floorNum == '0'){
			// 	Toast.show({
			// 		type: 'success',
			// 		content: '发成功'
			// 	});
			// }else{
				Toast.show({
					type: 'success',
					content: '发送成功'
				});
			//}
				
			//window.salt.router.goBack();
			setTimeout(function(){
				history.back();
			}, 	300);
			
		}).catch((error) => {
				Toast.show({
					type: 'error',
					content: error.errorMsg
				});
		});
	}

	handleChangeAnonymity(value) {
		if(value){
			value = "1";
			this.setState({
				isPetname: '0',
			});
		}else{
			value = "0";
		}
	    this.setState({
	      isAnonymity: value,
	    });
	}

	handleChangePetname(value) {
		DB.ForumModuleAPI.ifPetname({
			}).then((content) => {
				if(content.petName == ''){
					this.setState({
						isPetname: '0',
					  });
					Toast.show({
						type: 'error',
						content: '您的昵称为空，不可选择昵称评论或回复方式'
					});
				}else{
					if(value){
						value = "1";
						this.setState({
							isAnonymity: '0',
						});
					}else{
						value = "0";
					}
					this.setState({
					  isPetname: value,
					});
				}
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: '获取昵称出错'
				});
		})
	}

	/**
	 * 取消提交表单
	 * @return {[type]}
	 */
	handleCancel() {
		history.back();
	}

	render() {
		let t = this;
		return (
			<div className="page-add">
				<Group>
	        <Group.List >
	        {
	        	this.state.floorNum == '0'?
	        	 <TextareaField
	            required
	            label="内容"
	            readOnly={false}
	            layout="v"
	            minRows={8} maxRows={11}
	            placeholder="请输入..."
	            value={this.state.form.content}
	            onChange={this.handleTextAreaChange.bind(this, 'content', 5000,'0')} >
				{/*<Count total={300} length={this.state.form.content.length} />*/}
				<Count total={5000} length={this.state.form.content.length} />
	          </TextareaField>
	          :
	           <TextareaField
	            required
	            label="内容"
	            readOnly={false}
	            layout="v"
	            minRows={8} maxRows={11}
	            placeholder={this.state.floorNum}
	            value={this.state.form.content}
	            onChange={this.handleTextAreaChange.bind(this, 'content', 200,'1')} >
	            <Count total={200} length={this.state.form.content.length} />
	          </TextareaField>
	        }
	         
	        </Group.List>
	        {
	        	this.state.floorNum == '0'?
	        	 <Group.List className="t-PB16">
				<Upload 
    			uploadType="image" 
    			label="图片"
    			initList={this.state.form.attIdJson} 
    			dir="forum" 
    			onChange={this.handleChangePic.bind(this,'attIdJson')} 
    			onDel={this.handleChangePic.bind(this,'attIdJson')}
    			fileSizeLimit="10"
    			canAdd="true" canDel="true" limitNo="9"
    			ref="upload"
    			/>
			</Group.List>
			:
			''
			}
			<Group.List className={t.state.isShowAnonymity == 1 ? "" : "t-DN"}> 
	           <SwitchField
	           label="是否匿名"
	           on={t.state.isAnonymity == 1 ? true : false}
	            onChange={t.handleChangeAnonymity.bind(this)}
	         />
	        </Group.List>
			<Group.List className={t.state.isShowPetname == 1 ? "" : "t-DN"}> 
				<SwitchField
					label="是否昵称"
					on={t.state.isPetname == 1 ? true : false}
					onChange={t.handleChangePetname.bind(this)}
				/>
			</Group.List>	
				</Group>
				<div>
					<Button.Group className="page-add">
					  <Button type="secondary" display="inline"
					         onClick={this.handleCancel.bind(this)}>取消</Button>
					  <Button type="primary" display="inline"
					         onClick={this.handleSubmit.bind(this)}>发送</Button>
					</Button.Group>
				</div>	
			
			</div>

		);
		
	}
}